package com.sopaths.crawler.conf;

import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.sopaths.crawler.tasks.CrawlerTask;
import com.sopaths.crawler.thread.CrawlerTaskExecutor;

public class StartupJob implements Job {

	private CrawlerTaskExecutor taskExecutor;

	private List<CrawlerTask<?>> tasks;

	private final Logger logger = Logger.getLogger(StartupJob.class);

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			logger.info("Start crawling...");
			for (CrawlerTask<?> task : tasks) {
				taskExecutor.submit(task);
			}
		} catch (Exception ex) {
			logger.error("An error occurred while executing startup job.", ex);
			if (JobExecutionException.class.isInstance(ex)) {
				throw ex;
			}
			throw new JobExecutionException(ex);
		}
	}

	public void setTaskExecutor(CrawlerTaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}

	public void setTasks(List<CrawlerTask<?>> tasks) {
		this.tasks = tasks;
	}

}
